import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_demo/config/string.dart';
import 'package:flutter_demo/navigation/nav_page.dart';
import 'package:flutter_demo/pages/discovery/discovery_page.dart';
import 'package:flutter_demo/pages/discovery/record_page1.dart';
import 'package:flutter_demo/pages/home/home_page.dart';
import 'package:flutter_demo/pages/mine/mine_page.dart';
import 'package:flutter_demo/provider/globle_model.dart';
import 'package:flutter_demo/provider/tab_navigation_model.dart';
import 'package:flutter_demo/provider_widget.dart';
import 'package:flutter_demo/widget/ToastUtil.dart';
import 'package:provider/provider.dart';

import '../pages/discovery/discovery_page.dart';
import '../pages/discovery/record_page.dart';

class TabNavigation extends StatefulWidget {
  @override
  _TabNavigationState createState() => _TabNavigationState();
}

class _TabNavigationState extends State<TabNavigation> {
  PageController _pageController = PageController();

  DateTime lastTime;

  @override
  Widget build(BuildContext context) {
    final globalModel = Provider.of<GlobalModel>(context);
    return WillPopScope(
      onWillPop: _onWillPop,
      child: Scaffold(
        key: globalModel.globalKey,
        drawer: Drawer(child: NavPage(),),
        body: PageView(
          controller: _pageController,
          physics: NeverScrollableScrollPhysics(),
          children: <Widget>[HomePage(), RecordPage(),DiscoveryPage()],
        ),
        bottomNavigationBar: ProviderWidget<TabNavigationModel>(
            model: TabNavigationModel(),
            builder: (context, model, child) {
              return BottomNavigationBar(
                currentIndex: model.currentIndex,
                onTap: (index) {
                  if (model.currentIndex != index) {
                    _pageController.jumpToPage(index);
                    model.changeBottomTabIndex(index);
                  }
                },
                type: BottomNavigationBarType.fixed,
                //显示标题
                items: [
                  _bottomItem(DString.hot, Icons.home, Icons.home),
                  _bottomItem(DString.discover, Icons.find_in_page, Icons.find_in_page),
                  _bottomItem(DString.record, Icons.radio, Icons.radio),
                ],
              );
            }),
      ),
    );
  }

  _bottomItem(String title, IconData normalIcon, IconData selectIcon) {
    return BottomNavigationBarItem(
        icon: Icon(normalIcon,size: 24,),
        activeIcon: Icon(
          selectIcon,
          color: Colors.blue,
          size: 24,
        ),
        title: Text(title));
  }

  Future<bool> _onWillPop() async {
    if (lastTime == null || DateTime.now().difference(lastTime) > Duration(seconds: 2)) {
      lastTime = DateTime.now();
      ToastUtil.showTip(DString.exit_tip);
      return false;
    } else {
      SystemNavigator.pop();
      return true;
    }
  }

}
